package com.agrm.good.controller;

import com.agrm.api.client.BrandClient;
import com.agrm.api.client.CategoryClient;
import com.agrm.good.service.GoodService;
import com.agrm.model.brand.pojo.Brand;
import com.agrm.model.category.pojo.Category;
import com.agrm.model.common.dtos.PageRequestDto;
import com.agrm.model.common.dtos.PageResponseResult;
import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.good.pojo.Good;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/good")
public class GoodController {

    //TODO 商品添加Redis缓存

    @Autowired
    private GoodService goodService;
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private CategoryClient categoryClient;


    /**
     * 查询所有商品信息
     * @return
     */
    @GetMapping("/getAll")
    public ResponseResult getAll(){
        return ResponseResult.okResult(goodService.list());
    }


    /**
     * 商品分页搜索
     * @param pageRequestDto
     * @param name
     * @return
     */
    @GetMapping("/getGoodBySearch")
    public PageResponseResult getGoodBySearch(PageRequestDto pageRequestDto , String name){
        pageRequestDto.checkParam();
        return goodService.getGoodBySearch(pageRequestDto,name);
    }


    /**
     * 根据id查询单个商品（不包含分类和品牌信息）
     * @param id
     * @return
     */
    @GetMapping("/get")
    public ResponseResult getById(Integer id) {
        return ResponseResult.okResult(goodService.getById(id));
    }


    /**
     * 查询商品信息 包含所属分类和品牌
     * @param id
     * @return
     */
    @GetMapping("/getDetail")
    public ResponseResult getDetailById(@Param("id") Integer id) {
        Good good = goodService.getGoodDetailById(id);
        return ResponseResult.okResult(good);
    }

    @GetMapping("/getSeckill")
    public ResponseResult findAllSeckill() {
        List<Good> goods = goodService.findAllSeckill();

        return ResponseResult.okResult(goods);
    }

    /**
     * 获取商品详情图片
     * @param id
     * @return
     */
    @GetMapping("/getDetailsPicture")
    public ResponseResult getDetailsPicture(@Param("id") Integer id){
        Good good = goodService.getGoodDetailById(id);
        String detailPicture = good.getDetailPics();
        String[] split = detailPicture.split(",");
        return ResponseResult.okResult(split);
    }

    @GetMapping("/getSeckillGoodById/{id}")
    public ResponseResult getSeckillGoodById(@PathVariable("id") Integer id) {
        Good good = this.goodService.findSeckillById(id);
        if (good != null) {
            make(good);
            return ResponseResult.okResult(good);
        } else {
            return ResponseResult.okResult(null);
        }
    }


    /**
     * 商品更新
     * @param good
     * @return
     */
    @PutMapping("/update")
    public ResponseResult update(@RequestBody Good good) {
        good.setUpdatedTime(LocalDateTime.now());
        return ResponseResult.okResult(goodService.updateById(good));
    }

/**
 * 更新商品数量的接口方法
 * 通过商品ID和数量变化值来更新库存
 * @param goodId 商品ID，通过路径变量传递
 * @param delta 数量变化值，正数表示增加，负数表示减少，通过路径变量传递
 * @return 返回操作结果，包含更新是否成功的信息
 */
    @PutMapping("/updateQty/{goodId}/{delta}")    // 定义HTTP PUT请求映射，路径为/updateQty/{goodId}/{delta}
    public ResponseResult updateQty(@PathVariable("goodId") Integer goodId,     // 从路径中获取商品ID参数
                                 @PathVariable("delta") Integer delta) {        // 从路径中获取数量变化参数
        return ResponseResult.okResult(goodService.updateQty(goodId,delta));    // 调用服务层方法更新商品数量，并返回操作结果
    }


    /**
     * 商品添加
     * @param good
     * @return
     */
    @PostMapping("/add")
    public ResponseResult add(@RequestBody Good good) {
        good.setCreatedTime(LocalDateTime.now());
        good.setUpdatedTime(LocalDateTime.now());
        return ResponseResult.okResult(goodService.save(good));
    }


    /**
     * 商品删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delete")
    public ResponseResult delete(@RequestBody List<Integer> ids){
        return ResponseResult.okResult(goodService.removeByIds(ids));
    }

    /**
     * 根据分类ID查询该分类下的所有商品
     * @param categoryId 分类ID
     * @return 商品列表
     */
    @GetMapping("/getByCategoryId")
    public ResponseResult getGoodsByCategoryId(@RequestParam("categoryId") Integer categoryId) {
        List<Good> goods = goodService.getGoodsByCategoryId(categoryId);
        return ResponseResult.okResult(goods);
    }


    /**
     * 获取商品列表
     */
    @PostMapping("getPromoGood")
    public ResponseResult getPromoGood(@RequestBody String categoryName) {
        return goodService.getPromoGood(categoryName);
    }


    @PostMapping("getHotGood")
    public ResponseResult getHotGood(@RequestBody Map<String, List<String>> categoryName) {
        return goodService.getHotGood(categoryName.get("categoryName"));
    }



    private void make(Good good) {
        if (good.getBrandId() != null) {
            ResponseResult<Brand> brandResponseResult = brandClient.findById(good.getBrandId());
            Brand brand = brandResponseResult.getData();
            if (brand != null) {
                good.setBrand(brand);
            }
        }

        if (good.getCategoryId() != null) {
            ResponseResult<Category> categoryResponseResult = categoryClient.getCategoryById(good.getCategoryId());
            Category category = categoryResponseResult.getData();
            if (category != null) {
                good.setCategory(category);
            }
        }
    }
}
